<template>
  <q-page class="q-pa-md">
    <div class="row q-gutter-md">
      <!-- 左侧控制面板 -->
      <div class="col-12 col-md-4">
        <q-card>
          <q-card-section>
            <div class="text-h6 q-mb-md">
              <q-icon name="verified" class="q-mr-sm" />
              格式校验工具
            </div>
            
            <!-- 文件选择 -->
            <q-file
              v-model="selectedFiles"
              label="选择要校验的文件"
              multiple
              accept=".dcm,.dicom,.nii,.nii.gz"
              @update:model-value="onFilesSelected"
              class="q-mb-md"
            >
              <template v-slot:prepend>
                <q-icon name="upload_file" />
              </template>
            </q-file>

            <!-- 拖拽上传区域 -->
            <q-card
              flat
              bordered
              class="q-pa-lg text-center cursor-pointer q-mb-md drag-area"
              @dragover.prevent
              @drop.prevent="onDrop"
              :class="{ 'drag-over': isDragOver }"
              @dragenter="isDragOver = true"
              @dragleave="isDragOver = false"
            >
              <q-icon name="cloud_upload" size="48px" color="grey-5" class="q-mb-md" />
              <div class="text-body1 text-grey-7">拖拽文件到此处</div>
              <div class="text-caption text-grey-5">支持 DICOM (.dcm) 和 NII (.nii, .nii.gz) 格式</div>
            </q-card>

            <!-- 校验选项 -->
            <q-card flat bordered class="q-mb-md">
              <q-card-section>
                <div class="text-subtitle2 q-mb-sm">校验选项</div>
                
                <q-checkbox
                  v-model="validationOptions.checkHeader"
                  label="文件头校验"
                  class="q-mb-sm"
                />
                <q-checkbox
                  v-model="validationOptions.checkMetadata"
                  label="元数据完整性"
                  class="q-mb-sm"
                />
                <q-checkbox
                  v-model="validationOptions.checkImageData"
                  label="图像数据校验"
                  class="q-mb-sm"
                />
                <q-checkbox
                  v-model="validationOptions.checkCompression"
                  label="压缩格式检查"
                  class="q-mb-sm"
                />
                <q-checkbox
                  v-model="validationOptions.deepScan"
                  label="深度扫描"
                  class="q-mb-sm"
                />
              </q-card-section>
            </q-card>

            <!-- 批量操作 -->
            <q-card v-if="fileList.length > 0" flat bordered class="q-mb-md">
              <q-card-section>
                <div class="text-subtitle2 q-mb-sm">批量操作</div>
                
                <q-btn-group spread class="q-mb-md">
                  <q-btn
                    color="primary"
                    icon="play_arrow"
                    label="开始校验"
                    @click="startValidation"
                    :loading="validating"
                    :disable="fileList.length === 0"
                  />
                  <q-btn
                    color="negative"
                    icon="clear"
                    label="清空列表"
                    @click="clearFiles"
                    :disable="validating"
                  />
                </q-btn-group>

                <q-btn-group spread>
                  <q-btn
                    color="info"
                    icon="download"
                    label="导出报告"
                    @click="exportReport"
                    :disable="!hasValidationResults"
                  />
                  <q-btn
                    color="warning"
                    icon="settings"
                    label="高级设置"
                    @click="showAdvancedSettings"
                  />
                </q-btn-group>
              </q-card-section>
            </q-card>

            <!-- 统计信息 -->
            <q-card v-if="validationStats" flat bordered>
              <q-card-section>
                <div class="text-subtitle2 q-mb-sm">校验统计</div>
                <q-list dense>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>总文件数</q-item-label>
                      <q-item-label>{{ validationStats.total }}</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>通过校验</q-item-label>
                      <q-item-label class="text-positive">{{ validationStats.passed }}</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>校验失败</q-item-label>
                      <q-item-label class="text-negative">{{ validationStats.failed }}</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item>
                    <q-item-section>
                      <q-item-label caption>警告</q-item-label>
                      <q-item-label class="text-warning">{{ validationStats.warnings }}</q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-card-section>
            </q-card>
          </q-card-section>
        </q-card>
      </div>

      <!-- 右侧结果显示区域 -->
      <div class="col-12 col-md-8">
        <q-card style="min-height: 600px;">
          <q-card-section>
            <div v-if="fileList.length === 0" class="flex flex-center" style="height: 500px;">
              <div class="text-center">
                <q-icon name="verified" size="64px" color="grey-5" class="q-mb-md" />
                <div class="text-h6 text-grey-6">医学影像格式校验</div>
                <div class="text-body2 text-grey-5">请选择或拖拽文件进行格式校验</div>
                <div class="text-caption text-grey-4 q-mt-sm">
                  支持DICOM和NII格式的完整性检查
                </div>
              </div>
            </div>
            
            <div v-else>
              <!-- 文件列表和校验结果 -->
              <div class="text-h6 q-mb-md">
                文件列表 ({{ fileList.length }})
                <q-linear-progress
                  v-if="validating"
                  :value="validationProgress"
                  color="primary"
                  class="q-mt-sm"
                />
              </div>

              <q-scroll-area style="height: 500px;">
                <q-list separator>
                  <q-item
                    v-for="(file, index) in fileList"
                    :key="index"
                    class="q-pa-md"
                  >
                    <q-item-section avatar>
                      <q-icon
                        :name="getFileIcon(file.name)"
                        :color="getFileIconColor(file.name)"
                        size="md"
                      />
                    </q-item-section>

                    <q-item-section>
                      <q-item-label>{{ file.name }}</q-item-label>
                      <q-item-label caption>
                        {{ formatFileSize(file.size) }} • {{ getFileType(file.name) }}
                      </q-item-label>
                      
                      <!-- 校验状态 -->
                      <div v-if="file.validationResult" class="q-mt-sm">
                        <q-badge
                          :color="getStatusColor(file.validationResult.status)"
                          :label="getStatusLabel(file.validationResult.status)"
                          class="q-mr-sm"
                        />
                        <span class="text-caption">
                          耗时: {{ file.validationResult.duration }}ms
                        </span>
                      </div>

                      <!-- 校验详情 -->
                      <div v-if="file.validationResult && file.validationResult.details" class="q-mt-sm">
                        <q-expansion-item
                          dense
                          expand-separator
                          :label="`详细信息 (${file.validationResult.details.length} 项)`"
                        >
                          <q-list dense>
                            <q-item
                              v-for="(detail, detailIndex) in file.validationResult.details"
                              :key="detailIndex"
                              dense
                            >
                              <q-item-section avatar>
                                <q-icon
                                  :name="getDetailIcon(detail.type)"
                                  :color="getDetailColor(detail.type)"
                                  size="sm"
                                />
                              </q-item-section>
                              <q-item-section>
                                <q-item-label caption>{{ detail.message }}</q-item-label>
                              </q-item-section>
                            </q-item>
                          </q-list>
                        </q-expansion-item>
                      </div>
                    </q-item-section>

                    <q-item-section side>
                      <div class="column items-end">
                        <!-- 校验进度 -->
                        <div v-if="file.validating" class="q-mb-sm">
                          <q-spinner color="primary" size="20px" />
                        </div>
                        
                        <!-- 操作按钮 -->
                        <q-btn-group v-if="!validating" flat>
                          <q-btn
                            size="sm"
                            flat
                            icon="visibility"
                            @click="previewFile(file)"
                            :disable="!file.validationResult || file.validationResult.status === 'error'"
                          />
                          <q-btn
                            size="sm"
                            flat
                            icon="delete"
                            @click="removeFile(index)"
                          />
                        </q-btn-group>
                      </div>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-scroll-area>
            </div>
          </q-card-section>
        </q-card>
      </div>
    </div>

    <!-- 高级设置对话框 -->
    <q-dialog v-model="showAdvancedDialog">
      <q-card style="min-width: 400px;">
        <q-card-section>
          <div class="text-h6">高级校验设置</div>
        </q-card-section>

        <q-card-section>
          <q-input
            v-model="advancedSettings.maxFileSize"
            label="最大文件大小 (MB)"
            type="number"
            class="q-mb-md"
          />
          
          <q-input
            v-model="advancedSettings.timeout"
            label="校验超时时间 (秒)"
            type="number"
            class="q-mb-md"
          />

          <q-select
            v-model="advancedSettings.strictness"
            :options="strictnessOptions"
            label="校验严格程度"
            class="q-mb-md"
          />

          <q-checkbox
            v-model="advancedSettings.generateThumbnail"
            label="生成缩略图"
            class="q-mb-sm"
          />

          <q-checkbox
            v-model="advancedSettings.extractMetadata"
            label="提取完整元数据"
          />
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="取消" v-close-popup />
          <q-btn color="primary" label="保存" @click="saveAdvancedSettings" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 接口定义
interface ValidationResult {
  status: 'success' | 'warning' | 'error'
  duration: number
  details: Array<{
    type: 'info' | 'warning' | 'error'
    message: string
  }>
}

interface FileWithValidation extends File {
  validating?: boolean
  validationResult?: ValidationResult
}

// 响应式数据
const selectedFiles = ref<File[] | null>(null)
const fileList = ref<FileWithValidation[]>([])
const validating = ref(false)
const validationProgress = ref(0)
const isDragOver = ref(false)
const showAdvancedDialog = ref(false)

// 校验选项
const validationOptions = ref({
  checkHeader: true,
  checkMetadata: true,
  checkImageData: false,
  checkCompression: true,
  deepScan: false
})

// 高级设置
const advancedSettings = ref({
  maxFileSize: 1000,
  timeout: 30,
  strictness: 'normal',
  generateThumbnail: false,
  extractMetadata: true
})

const strictnessOptions = [
  { label: '宽松', value: 'loose' },
  { label: '正常', value: 'normal' },
  { label: '严格', value: 'strict' }
]

// 计算属性
const validationStats = computed(() => {
  if (fileList.value.length === 0) return null
  
  const total = fileList.value.length
  const completed = fileList.value.filter(f => f.validationResult).length
  const passed = fileList.value.filter(f => f.validationResult?.status === 'success').length
  const warnings = fileList.value.filter(f => f.validationResult?.status === 'warning').length
  const failed = fileList.value.filter(f => f.validationResult?.status === 'error').length
  
  return { total, completed, passed, warnings, failed }
})

const hasValidationResults = computed(() => {
  return fileList.value.some(f => f.validationResult)
})

// 文件选择处理
const onFilesSelected = (files: File[] | null) => {
  if (!files) return
  addFiles(files)
}

// 拖拽处理
const onDrop = (event: DragEvent) => {
  isDragOver.value = false
  const files = Array.from(event.dataTransfer?.files || [])
  addFiles(files)
}

// 添加文件到列表
const addFiles = (files: File[]) => {
  const validFiles = files.filter(file => {
    const name = file.name.toLowerCase()
    return name.endsWith('.dcm') || 
           name.endsWith('.dicom') || 
           name.endsWith('.nii') || 
           name.endsWith('.nii.gz')
  })

  if (validFiles.length === 0) {
    $q.notify({
      type: 'warning',
      message: '未找到支持的文件格式',
      caption: '请选择 .dcm、.dicom、.nii 或 .nii.gz 文件'
    })
    return
  }

  // 避免重复添加
  const existingNames = new Set(fileList.value.map(f => f.name))
  const newFiles = validFiles.filter(f => !existingNames.has(f.name))

  fileList.value.push(...newFiles)

  $q.notify({
    type: 'positive',
    message: `已添加 ${newFiles.length} 个文件`
  })
}

// 开始校验
const startValidation = async () => {
  if (fileList.value.length === 0) return

  validating.value = true
  validationProgress.value = 0

  for (let i = 0; i < fileList.value.length; i++) {
    const file = fileList.value[i]
    file.validating = true

    try {
      const result = await validateFile(file)
      file.validationResult = result
    } catch (error) {
      file.validationResult = {
        status: 'error',
        duration: 0,
        details: [{ type: 'error', message: '校验过程中发生错误' }]
      }
    }

    file.validating = false
    validationProgress.value = (i + 1) / fileList.value.length
  }

  validating.value = false

  $q.notify({
    type: 'positive',
    message: '校验完成',
    caption: `共校验 ${fileList.value.length} 个文件`
  })
}

// 校验单个文件
const validateFile = async (file: File): Promise<ValidationResult> => {
  const startTime = Date.now()
  
  // 模拟校验过程
  await new Promise(resolve => setTimeout(resolve, Math.random() * 2000 + 500))
  
  const duration = Date.now() - startTime
  const fileType = getFileType(file.name)
  
  // 模拟校验结果
  const details: ValidationResult['details'] = []
  let status: ValidationResult['status'] = 'success'
  
  if (validationOptions.value.checkHeader) {
    if (fileType === 'DICOM') {
      details.push({ type: 'info', message: 'DICOM文件头校验通过' })
    } else {
      details.push({ type: 'info', message: 'NII文件头校验通过' })
    }
  }
  
  if (validationOptions.value.checkMetadata) {
    details.push({ type: 'info', message: '元数据完整性检查通过' })
  }
  
  // 随机生成一些警告或错误
  if (Math.random() < 0.2) {
    details.push({ type: 'warning', message: '检测到非标准元数据字段' })
    status = 'warning'
  }
  
  if (Math.random() < 0.1) {
    details.push({ type: 'error', message: '图像数据损坏或不完整' })
    status = 'error'
  }
  
  return { status, duration, details }
}

// 工具函数
const getFileType = (fileName: string): string => {
  const name = fileName.toLowerCase()
  if (name.endsWith('.dcm') || name.endsWith('.dicom')) return 'DICOM'
  if (name.endsWith('.nii') || name.endsWith('.nii.gz')) return 'NII'
  return 'Unknown'
}

const getFileIcon = (fileName: string): string => {
  const type = getFileType(fileName)
  return type === 'DICOM' ? 'medical_services' : 'psychology'
}

const getFileIconColor = (fileName: string): string => {
  const type = getFileType(fileName)
  return type === 'DICOM' ? 'primary' : 'secondary'
}

const getStatusColor = (status: string): string => {
  const colors: Record<string, string> = {
    success: 'positive',
    warning: 'warning',
    error: 'negative'
  }
  return colors[status] || 'grey'
}

const getStatusLabel = (status: string): string => {
  const labels: Record<string, string> = {
    success: '通过',
    warning: '警告',
    error: '失败'
  }
  return labels[status] || '未知'
}

const getDetailIcon = (type: string): string => {
  const icons: Record<string, string> = {
    info: 'info',
    warning: 'warning',
    error: 'error'
  }
  return icons[type] || 'help'
}

const getDetailColor = (type: string): string => {
  const colors: Record<string, string> = {
    info: 'info',
    warning: 'warning',
    error: 'negative'
  }
  return colors[type] || 'grey'
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 操作函数
const removeFile = (index: number) => {
  fileList.value.splice(index, 1)
}

const clearFiles = () => {
  fileList.value = []
  validationProgress.value = 0
}

const previewFile = (file: FileWithValidation) => {
  $q.notify({
    type: 'info',
    message: '预览功能',
    caption: '此功能将在后续版本中实现'
  })
}

const exportReport = () => {
  $q.notify({
    type: 'info',
    message: '导出报告',
    caption: '此功能将在后续版本中实现'
  })
}

const showAdvancedSettings = () => {
  showAdvancedDialog.value = true
}

const saveAdvancedSettings = () => {
  showAdvancedDialog.value = false
  $q.notify({
    type: 'positive',
    message: '设置已保存'
  })
}
</script>

<style scoped>
.drag-area {
  border: 2px dashed #ccc;
  transition: all 0.3s ease;
}

.drag-area.drag-over {
  border-color: #1976d2;
  background-color: rgba(25, 118, 210, 0.05);
}

.cursor-pointer {
  cursor: pointer;
}
</style>

